<template>
  <div class="home" ref="home">

  </div>
</template>

<script>

import * as THREE from 'three'
import {OrbitControls} from "three/addons/controls/OrbitControls.js";
import addGeoMetry from "./addGeoMetry.js";
import circle from "@/view/lesson4/line.js";
let camera = null
let renderer = null
export default {
  name: "lesson4",
  data() {
    return {
      R: 130,
      angle: 0,
      list: [{
        texture: 'img/diqiu.jpg',
        radius: 10,
        x: 150,
        name: '地球'
      }, {
        texture: 'img/taiyang.jpg',
        radius: 30,
        x: 0,
        name: '太阳'
      }],
    }
  },

  mounted() {
    this.initThree();
    window.addEventListener('resize', this.onWindowResize);
  },
  methods: {
    initThree() {
      var that = this;

      // 创建场景
      var scene = new THREE.Scene()

      this.list.forEach((type, index) => {
        var mesh = addGeoMetry(type.texture, type.radius, type.x)
        mesh.name = type.name
        scene.add(mesh); //网格模型添加到场景中
      });

      // 创建轨道
      var line = circle(that.R)
      scene.add(line)

      //环境光
      var ambient = new THREE.AmbientLight(0xffffff, 0.6);
      scene.add(ambient);
      /**
       * 相机设置
       */
      const width = this.$refs.home.clientWidth;
      const height = this.$refs.home.clientHeight;
      //创建相机对象
      camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
      camera.position.set(200, 300, 200); //设置相机位置
      camera.lookAt(scene.position); //设置相机方向(指向的场景对象)

      /**
       * 创建渲染器对象
       */
      renderer = new THREE.WebGLRenderer({
        antialias: true, //开启锯齿
      });
      renderer.setSize(width, height); //设置渲染区域尺寸
      this.$refs.home.appendChild(renderer.domElement);

      // 渲染函数
      function render() {
        scene.children.forEach((type) => {
          if (type.type == 'Mesh') {
            type.rotateY(0.01)
            if (type.name == '地球') {
              that.angle += 0.01;// 每次执行render角度新增加
              var x = that.R * Math.sin(that.angle);//地球x坐标计算
              var z = that.R * Math.cos(that.angle);//地球z坐标计算
              // 设置地球xz坐标，实现公转动画
              type.position.set(x, 0, z);
            }
          }
        });
        renderer.render(scene, camera); //执行渲染操作
        requestAnimationFrame(render); //请求再次执行渲染函数render，渲染下一帧
      }
      render();
      var controls = new OrbitControls(camera, renderer.domElement);
    },
    onWindowResize() {
      // Update camera
      const width = this.$refs.home.clientWidth;
      const height = this.$refs.home.clientHeight;
      camera.aspect = width / height;
      camera.updateProjectionMatrix();

      // Update renderer
      renderer.setSize(width, height);
    },
  },
}
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100%;
  background: #053d79;
  position: fixed;
}

</style>
